
import 'dart:typed_data';

import 'package:cloudapp/esdk/response/file_list_item.dart';
import 'package:device_info/device_info.dart';
import 'package:flutter/foundation.dart';
import 'package:image/image.dart' as image;
import 'dart:convert' as convert;

void showDeviceInfo() async {
  var devInfo = DeviceInfoPlugin();
  AndroidDeviceInfo info = await devInfo.androidInfo;
  print('version ${info.version}');
  print('board ${info.board}');
  print('bootloader ${info.bootloader}');
  print('brand ${info.brand}');
  print('device ${info.device}');
  print('display ${info.display}');
  print('fingerprint ${info.fingerprint}');
  print('hardware ${info.hardware}');
  print('host ${info.host}');
  print('id ${info.id}');
  print('manufacturer ${info.manufacturer}');
  print('model ${info.model}');
  print('product ${info.product}');
  print('tags ${info.tags}');
  print('type ${info.type}');
  print('isPhysicalDevice ${info.isPhysicalDevice}');
  print('androidId ${info.androidId}');
}

/// 客户端的图片裁切，将按比例缩放的缩略图，裁成正方形
image.Image cutCentered(image.Image source, int maxSize) {
  final double scaleX = source.width / maxSize;
  final double scaleY = source.height / maxSize;
  final double scale = ((source.height ~/ scaleX) > maxSize) ? scaleX : scaleY;
  final int width = source.width ~/ scale;
  final int height = source.height ~/ scale;

  image.Image resized = image.copyResize(source, width: width, height: height);
  var oW = resized.width;
  var oH = resized.height;

  var sX = 0;
  var sY = 0;

  if (oW > oH) {
    // 横屏图片
    sX = (oW - 60) ~/ 2;
  } else {
    // 竖屏图片
    sY = (oH - maxSize) ~/ 2;
  }

  return image.drawImage(
    new image.Image(maxSize, maxSize),
    resized,
    dstX: 0,
    dstY: 0,
    dstW: maxSize,
    dstH: maxSize,
    srcW: maxSize,
    srcH: maxSize,
    srcX: sX,
    srcY: sY,
  );
}

/// 传入缩略图，传出裁剪后的缩略图
Uint8List scaleImageCentered(Uint8List  data, {int maxSize = 80}) {
  final img = image.decodeImage(data);
  print('height: ${img.height}, width: ${img.width}');
  final out = cutCentered(img, maxSize);
  return image.encodeJpg(out);
}

String scaleImageInThread80(String thumb) {
  final data = convert.base64Decode(thumb);
  final c = scaleImageCentered(data, maxSize: 80);
  return convert.base64Encode(c);
}

List<FileListItem> scaleThumbs(List<FileListItem> rs) {
  var out = List<FileListItem>();
  for(var item in rs) {
    var nItem = item;
    if(item.thumb.isNotEmpty) {
      nItem.thumbSquare = scaleImageInThread80(item.thumb);
    }
    out.add(nItem);
  }

  return out;
}
